// 发送节目单的单线程模块

#include <thr_list.h>
#include <proto.h>
#include <stdio.h>
#include <stdlib.h>
#include <server_conf.h>
#include <pthread.h>
#include <media_lib.h>
#include <syslog.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netinet/in.h>

static pthread_t tid_list;  // 节目单发送线程标志符
static int nr_list_ent = 0; // 节目个数\频道概览信息条数
static struct mlib_listentry_st* list_ent = NULL;  // 首个频道概览信息

static void* thr_list(void* arg) {
    int i = 0;
    int totalSize = 0;  // 频道总览信息字节数
    struct msg_list_st* entlistp = NULL;   // 频道总览信息
    struct msg_listentry_st* entryp = NULL;
    ssize_t ret = -1;
    int size = 0;

    totalSize = sizeof(chnid_t);    // 频道总览信息中chnid字节数
    for (i = 0; i < nr_list_ent; i++) {
        totalSize += sizeof(struct msg_listentry_st) + strlen(list_ent[i].desc);
    }
    // syslog(LOG_INFO, "totalSize:%d\n", totalSize);

    entlistp = (struct msg_list_st*)malloc(totalSize);
    if (entlistp == NULL) {
        syslog(LOG_ERR, "malloc error,%s\n", strerror(errno));
        exit(1);
    }
    entlistp->chnid = LSITCHNID;

    entryp = entlistp->entry;
    for (i = 0; i < nr_list_ent; i++) {
        size = sizeof(struct msg_listentry_st) + strlen(list_ent[i].desc);
        entryp->chnid = list_ent[i].chnid;
        entryp->len = htons(size);
        strncpy(entryp->desc, list_ent[i].desc, strlen(list_ent[i].desc));
        syslog(LOG_INFO, "i:%d,chnid:%d,len:%d,desc:%s\n", i, entryp->chnid, entryp->len, entryp->desc);
        entryp = (void*)((char*)entryp + size);
    }

    while (1) {
        ret = sendto(serverSd, entlistp, totalSize, 0, (void*)&sndAddr, sndAddrLen);
        if (ret < 0) {
            syslog(LOG_ERR, "sendto error,%s\n", strerror(errno));
            exit(1);
        }
        sleep(1);
    }
}

/*
 \brief 创建线程，广播多个频道的概览信息
 \param ptr:首个频道的概览信息地址
 \param list_size:频道的个数
*/
int thr_list_create(struct mlib_listentry_st* ptr, int list_size) {
    int err;
    list_ent = ptr;
    nr_list_ent = list_size;
    err = pthread_create(&tid_list, NULL, thr_list, NULL);
    if (err != 0) {
        syslog(LOG_ERR, "pthread_create error,%s\n", strerror(errno));
        return -1;
    }
    return 0;
}

int thr_list_destroy(void) {
    pthread_cancel(tid_list);
    pthread_join(tid_list, NULL);
    
    return 0;
}